package exercise02;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class EmployerServiceI implements EmployerService {
    @Autowired
    private EmployerDao ed;

    /**
     * 计算出每一个员工的年龄
     * @return
     */
    public List<Employer> findEmployer() {
        Calendar c = Calendar.getInstance();//获取当前系统时间
        int nowYear = c.get(Calendar.YEAR);
        List<Employer> list = ed.findEmployer();
        List<Employer> lis = new ArrayList<Employer>();
        //遍历员工的集合
        for (Employer e:list) {
            //获取员工出生日期
            Date birthday = e.getBirthday();
            c.setTime(birthday);//把出生日期转换为出生日历
            int age = nowYear - c.get(Calendar.YEAR);
            e.setAge(age);
            lis.add(e);//修改后，添加回集合
        }
        return lis;
    }

    /**
     * 计算所有员工的平均工资
     * @return
     */
    public double calcAvgSalary() {
        double sum = 0d,avg = 0d;
        List<Employer> list = ed.findEmployer();
        //遍历集合
        for(int i = 0;i < list.size();i++){
            //获取出员工
            Employer e = list.get(i);
            double salary = e.getSalary();//获取每一个员工工资
            sum += salary;//计算总和  sum = sum + salary;
        }
        avg = sum / (list.size()==0?1:list.size());//小心：除数不能为0
        //保留一位小数
        avg = Math.round(avg*10)*1.0D/10;
        return avg;
    }
}
